<template>
  <div class="upload-page w-100">
    <el-container>
      <el-main
        v-loading="loading"
        element-loading-text="..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <div class="report-toolbar flex items-center justify-s-between">
          <div></div>
          <div style="display: flex">
            <!-- <el-button class="m-r" size="mini" @click="showCityDialog" style="background:#79A2E6;border-color:#79A2E6;color:#fff;">
              选择对标城市
            </el-button> -->
              <el-button class="m-r" size="mini" @click="showCityDialog" style="color:#fff;" type="primary">
              选择对标城市
            </el-button>
          </div>
        </div>
        <div class="main-table">
          <div class="city-table-box" id="data-table">
            <el-table :data="tableData" stripe style="width: 100%" :height=" tableHeight " size='mini' >
              <el-table-column type="index" label="序号" width="100px" align="center" ></el-table-column>
              <el-table-column prop="markCityName" label="地级市名称" align="center" ></el-table-column>
              <el-table-column label="操作" min-width="40%" align="center" >
                <template slot-scope="scope">
                  <el-button @click="deleteCity(scope.row)" type="text" size="small">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        <!-- 弹框 -->
        <el-dialog
          title="选择对标城市"
          :visible.sync="cityDialog"
          width="650px"
          @closed="cancelForm"
          class="city-dialog"
          :close-on-click-modal="false"
        >
          <div class="city-tree">
            <div class="city-tree-left">
              <div class="left-search-box">

                <el-col :span="18">
                  <el-input
                    placeholder="输入地级市关键字搜索"
                    v-model="cityWord"
                    clearable
                  >
                  </el-input>
                </el-col>

                <el-checkbox v-model="showRecommend" @change="changeWord(cityWord)">推荐</el-checkbox>
              </div>

              <el-tree
                v-if="showTree1"
                ref="cityTree1"
                :data="treeData1"
                :props="defaultProps1"
                show-checkbox
                node-key="id"
                :default-expanded-keys="leftExpandedList"
                :default-checked-keys="leftCheckedList"
                :filter-node-method="filterNode"
                @check="chooseCity"
                @node-click="clickLeftNode"

              >
               <span class="city-tree-left-node" slot-scope="{ data }">
                <span>{{ data.name }}</span>
                <span class="recommend-icon" v-show="data.recommendType == 1">推</span>
              </span>

              </el-tree>
            </div>
            <div>
              <i class="el-icon-sort" ></i>
            </div>
            <div class="city-tree-right">
              <div>
                <span>已选: </span>
                <span >{{ treeData2.length }}</span>/<span>{{ maxLen }}</span>
              </div>
              <div>
                <el-tree
                  ref="cityTree2"
                  :data="treeData2"
                  :props="defaultProps2"
                  @node-click="delRightCity"
                >

                </el-tree>
              </div>

            </div>

          </div>
          <div slot="footer">
            <el-button @click="cancelForm">取消</el-button>
            <el-button  type="primary" @click="setTableList" :loading="sendListLoading">确定</el-button>
          </div>
        </el-dialog>

      </el-main>
    </el-container>
  </div>
</template>

<script>
// var gisObj
import { mapGetters, mapState } from 'vuex'

export default {
  data() {
    return {
      tableHeight: 100,

      tableData: [ ],
      loading: false,

      // 弹窗数据
      cityDialog: false,
      sendListLoading: false,
      cityWord: '',
      showRecommend: false,
      maxLen: 10,
      // 正在获取左侧列表
      getLoding: false,
      showTree1: true,
      // 左侧城市列表
      treeData1: [],
      // 左侧城市已选中列表
      leftCheckedList: [],
      // 左侧需要展开的省
      leftExpandedList: [],
      defaultProps1: {
        children: 'depCityList',
        label: 'name',
        disabled: this.disabledFn
      },
      // 右侧城市列表
      treeData2: [],
      defaultProps2: {
        children: 'depCityList',
        label: 'name',
      },
    }
  },
  computed: {
    ...mapState(['home']),
    ...mapGetters(['userInfo' ])
  },
  watch: {
    cityWord( nv ) {
      this.changeWord(nv);
    }
  },
  mounted() {
    let resize=() => {
      this.autoTableHeight()
    }
    this.$once('hook:beforeDestroy',()=>{
        window.removeEventListener('resize',resize)
      })
    window.addEventListener('resize',resize)

    this.getMarkCityList();
  },
  methods: {
    // 表格是否禁用
    disabledFn() {
      return this.treeData2.length >= this.maxLen;
    },
    // 表格高度自适应
    autoTableHeight() {

      this.tableHeight = document.getElementsByClassName(
        'city-table-box'
      )[0].clientHeight
    },

    // 删除当前城市
    deleteCity( city, i ) {
      this.$confirm('一旦删除将不可恢复，确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let obj = {
            cityId: city.cityId,
            markCityId: city.markCityId,
          }
          this.api.delMarkCity(obj)
              .then((res) => {
                if(res.code == 1) {
                  this.getMarkCityList();
                }
              })

        }).catch(() => {
        });

    },

    // 显示弹框
    async showCityDialog() {
      let cityList = this.tableData;
      let  treeData2 = [];
      cityList.forEach(item => {
        treeData2.push({
          id: item.markCityId,
          name: item.markCityName
        })
      });
      this.treeData2 = treeData2;
      this.getProvinceCity();
      this.cityDialog  = true;

    },

    // 获取 对标城市列表
    getMarkCityList( obj={} ) {
      this.api.getMarkCityList(obj)
          .then((res) => {
            if(res.code == 1) {
              this.tableData = res.data;

              this.autoTableHeight();
            }
          })
    },
    // 获取搜索后的城市
    async getSearchCity(obj) {
      await this.getProvinceCity(obj);
    },

    // 获取 可选对标城市列表库
    getProvinceCity( obj={} ) {
      this.getLoding = true;
      return this.api.getProvinceCity(obj)
          .then((res) => {
            if(res.code == 1) {
              // 遍历数组 选出已选的列表 已选的城市列表需打开
              let checkedList = [];
              let expandedList = [];

              res.data.forEach( item => {
                let showExpand = false;
                item.depCityList.forEach(city => {
                  if( city.type == 1 ) {
                    checkedList.push(city.id);
                    showExpand = true;
                  }
                });
                if(showExpand) {
                  expandedList.push(item.id);
                }

              });
              this.leftCheckedList = checkedList;
              this.leftExpandedList = expandedList;
              this.treeData1 = res.data;
              this.getLoding = false;
              return true;
            }
          })
    },


    // 关闭弹框
    cancelForm() {
      this.cityDialog = false
    },

    //点击左边节点 点击文字切换选中 (功能只有市级有)
    clickLeftNode(node) {
      if( !node.depCityList ) {
        let obj = {
          checkedKeys: this.$refs.cityTree1.getCheckedKeys(),
          checkedNodes: this.$refs.cityTree1.getCheckedNodes()
        }
        // 市节点，先判断添加还是取消，
        let judgeList = obj.checkedKeys.filter( v => { return v == node.id } )
        if( judgeList.length == 0 && this.treeData2.length < 10  ) {
          this.$refs.cityTree1.setChecked(node.id, true);
        }else {
          this.$refs.cityTree1.setChecked(node.id, false);
        }
        obj = {
          checkedKeys: this.$refs.cityTree1.getCheckedKeys(),
          checkedNodes: this.$refs.cityTree1.getCheckedNodes()
        }
        this.chooseCity(node, obj);
      }
    },
    // 选择城市
    chooseCity(node, { checkedKeys, checkedNodes,  }) {
      if( node.depCityList ) {
        // 省节点 需要按顺序添加 多的取消选择

        let currentTreeData = JSON.parse(JSON.stringify(this.treeData2));  //点击前已存的右侧城市
        let keysList = currentTreeData.map( v => { return  v.id  } );  //点击前已选的key值数组
        node.depCityList.forEach( (item, i) => {
          if( this.treeData2.length < 10 ) {
            let checked = false;
            currentTreeData.forEach( (city, j) => {
              if( item.id == city.id ) {
                checked = true;
                currentTreeData.splice(j, 1);
              }
            });
            if( !checked ) {
              // 给选中的城市添加进选中数组
              keysList.unshift( item.id )
              // 往右侧列表添加城市数据;
              this.$refs.cityTree2.data.unshift({
                name: item.name,
                id: item.id
              })
            }
          }
        });
        // 最后设置 右侧列表中出现的选中城市， 多的取消选择
        this.$refs.cityTree1.setCheckedKeys( keysList );

      }else {
        // 市节点，先判断添加还是取消，
        let judgeList = checkedKeys.filter( v => { return v == node.id } )
        // console.log(judgeList)
        if( judgeList.length == 0 ) {
          // 取消城市,
          let treeData2 = this.treeData2;
          treeData2.forEach( (item, i) => {
            if( item.id == node.id ) {
              this.$refs.cityTree2.data.splice(i, 1);
            }
          });

        }else {
          // 添加城市
          this.$refs.cityTree2.data.unshift({
            name: node.name,
            id: node.id
          })


        }
      }
    },

    // 删除右侧城市
    delRightCity(node) {
      let index = -1;
      this.treeData2.filter( (obj,i) => {
        if( obj.id == node.id ) {
          index = i;
        }
        return obj.id == node.id
      })

      if( index != -1 ) {
        this.$refs.cityTree1.setChecked(node.id, false);
        this.$refs.cityTree2.data.splice(index, 1);

      }

    },
    // 更改搜索词 调用树形图过滤
    changeWord(val) {
      let obj = {
        value: val,
        showRecommend: this.showRecommend
      }
      console.log(obj);


      if( !obj.value && !obj.showRecommend) {
        // 调用只打开选中节点的方法
        this.reloadTree(this.$refs.cityTree1.getCheckedKeys());
        console.log( this.$refs.cityTree1.getCheckedKeys()  )
      }else {
        this.$refs.cityTree1.filter( obj );
      }
    },
    // 搜索词过滤
    filterNode(obj, data, node) {
      // console.log(node);

      if ( !obj.showRecommend && !obj.value ) return true;
      // 省级直接跳过
      if (data.depCityList) return false;

      // 如果是推荐城市 需要在推荐城市中筛选
      if(obj.showRecommend) {
        // console.log(data.recommendType);
        return data.recommendType == 1 && data.name.indexOf(obj.value) !== -1 ;
      }
      return data.name.indexOf(obj.value) !== -1;
    },

    // 调用重加载方法 保留加载前勾选和勾选的父节点打开的状态
    reloadTree(checkedList) {
      let list = this.treeData1;
      let expandedList = [];

      list.forEach( item => {
        let showExpand = false;
        checkedList.forEach(id => {
          if( id.substr(0,2) == item.id.substr(0,2) ) {
            showExpand = true;
          }
        });
        if(showExpand) {
          expandedList.push(item.id);
        }

      });
      this.leftCheckedList = checkedList;
      this.leftExpandedList = expandedList;

      this.showTree1 = false;
      this.$nextTick(() => {
        this.showTree1 = true;
      })
    },

    // 提交列表
    setTableList() {
      this.sendListLoading = true;
      let tableData = [];
      let list = this.treeData2;
      list.forEach( (item, i) => {
        tableData.push({
          markCityId: item.id,
          markCityName: item.name,
          sort: i + 1
        })
      });
      let params = {
        cityId: this.userInfo.cityId,
        markCityList: tableData
      }

      this.api.saveMarkCityList(params)
            .then(res => {
              if(res.code == 1) {
                this.cityDialog = false;
                this.getMarkCityList();
              }
              this.sendListLoading = false;
            })
    }

  }
}
</script>

<style lang="scss" scoped>
.upload-page {
  .el-main {
    display: block;
    background-color: #fff;
    height: 100%;
  }
  .report-toolbar {
    padding: 0 15px;
    height: 52px;
  }
  .main-table {
    height: calc(100% - 62px);
    padding:0 15px 15px 15px;
    .city-table-box {
      height: calc(100% - 28px);
    }
  }
}


// 选择对标城市的弹窗
.city-tree {
  display: flex;
  justify-content: space-between;
  align-items: center;
  > div:nth-child(2) {
    margin: 0 20px;
    > i {
      transform: rotate(90deg);
      font-size: 20px;
    }
  }
  .city-tree-left,
  .city-tree-right {
    width: 45%;
    height: 324px;
    display: flex;
    flex-flow: column;
    justify-content: space-between;
  }

  .city-tree-left {
    border: 1px solid #999;
    padding: 10px;
    .left-search-box {
      height: 36px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px
    }
    > div:nth-child(2) {
      flex: 1;
      overflow-y: auto;
    }

    // 左侧节点样式
    .city-tree-left-node {

      // 推荐图标样式
      .recommend-icon {
        background-color: #eed014;
        padding: 0 3px;
        border-radius: 4px;
        font-size: 12px;
        margin-left: 10px;
      }
    }

  }

  .city-tree-right {

    > div:first-child {
      height: 30px;
      padding: 5px 10px;

      > span:nth-child(2) {
        color: #409EFF;
      }
    }
    > div:nth-child(2) {
      flex: 1;
      overflow: hidden;
      border: 1px solid #999;
      padding: 5px 10px;

    }
  }

}
</style>
